<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\Role;
use App\Models\UserRole;


class UserController extends Controller
{
    //用户列表
    public function userList(Request $request){
        $where = function ($query) use ($request) {
            //用户名
            if ($request->has('username') and $request->username != '') {
                $search = "%" . $request->username . "%";
                $query->where('username', 'like', $search);
            }
            //真实姓名
            if ($request->has('realname') and $request->realname != '') {
                $search = "%" . $request->realname . "%";
                $query->where('realname', 'like', $search);
            }
            //手机号
            if ($request->has('cellphone') and $request->cellphone != '') {
                $search = "%" . $request->cellphone . "%";
                $query->where('cellphone', 'like', $search);
            }
        };
        $allUser=User::where($where)->with('roles')->paginate(10);
        return view('admin.user.userList',compact('allUser'));
    }
    //新建用户
    public function createUser(Request $request){
        $allRole=Role::all();
        return view('admin.user.createUser',compact('allRole'));
    }
    //保存用户
    public function saveUser(Request $request){
        return User::checkUser($request);
    }

    //编辑用户
    public function editUser(Request $request){
        $arr=explode('=',$request->userId);
        $userId=$arr['1'];
        $editUser=User::where('id',$userId)->first();
        return view('admin.user.editUser',compact('editUser'));
    }

    //更新用户
    public function updateUser(Request $request){
        return User::updateUser($request);
    }

    //删除用户
    public function deleteUser(Request $request){

        $deleteUser=User::destroy($request->userId);
        if($deleteUser){
            $backMsg=['msg'=>200];
            return json_encode($backMsg);
        }
    }

    //给角色添加权限
    public function addRole(Request $request){
        $arr=explode('=',$request->userId);
        $userId=$arr['1'];
        $allRole=Role::all();
        return view('admin.user.addRole',compact('allRole','userId'));
    }
    //给角色添加权限
    public function checkRole(Request $request){
        return User::checkRole($request);
    }

}
